package com.bsoft.gol.editor.filter;

import com.bsoft.gol.editor.utils.UserRoleTokenUtils;
import ctd.account.UserRoleToken;
import ctd.spring.AppDomainContext;
import ctd.util.ServletUtils;
import ctd.util.context.ContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.filter.OncePerRequestFilter;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * restful api token解析过滤器
 *
 * @author neoLin - 2022/06/13 09:28
 **/
@Slf4j
public class EditorRestUserTokenFilter extends OncePerRequestFilter {

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    private List<String> excludeUrlPatterns;

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
            if(CollectionUtils.isEmpty(excludeUrlPatterns)){
                return false;
            }
            return excludeUrlPatterns.stream()
                    .anyMatch(p -> pathMatcher.match(p, request.getServletPath()));
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        try {
            UserRoleToken token = UserRoleTokenUtils.getUserRoleToken(request);
            String currentDeptId = UserRoleTokenUtils.getCurrentDeptId(request);

            Map<String, Object> headers = new HashMap();
            headers.put("$uid", token.getUserId());
            headers.put("$urt", token.getId());
            headers.put("$tenantId", token.getTenantId());
            headers.put("currentDeptId", currentDeptId);
            headers.put("$clientIpAddress", ServletUtils.getIpAddress(request));
            headers.put("$fromDomain", AppDomainContext.getName());
            headers.put("$ur", token);

            ContextUtils.put("$rpcInvokeHeaders", headers);
            ContextUtils.put("$ur", token);
            ContextUtils.put("currentDeptId", currentDeptId);
            ContextUtils.put("$clientIpAddress", ServletUtils.getIpAddress(request));
            ContextUtils.put("$fromDomain", AppDomainContext.getName());
        } catch (Exception e) {
            log.debug("解析token失败,{}", e.getMessage());
        }
        filterChain.doFilter(request, response);
    }

    public void setExcludeUrlPatterns(List<String> excludeUrlPatterns) {
        this.excludeUrlPatterns = excludeUrlPatterns;
    }
}
